package com.xyzwps.example.stream;

import java.util.Objects;
import java.util.function.Function;

public class MapOperator<T, R> implements Operator<T, R> {

    private final Function<T, R> mapFn;

    public MapOperator(Function<T, R> mapFn) {
        this.mapFn = Objects.requireNonNull(mapFn);
    }

    @Override
    public Stream<R> handle(Stream<T> origin) {
        return new Stream<>() {
            @Override
            public Parcel<R> next() {
                return switch (origin.next()) {
                    case Parcel.Done<T> ignored -> Parcel.done();
                    case Parcel.Failure<T> failure -> Parcel.failed(failure.cause());
                    case Parcel.Delivery<T> delivery -> Parcel.deliver(mapFn.apply(delivery.value()));
                };
            }
        };
    }
}
